package com.smartpower.wattmeter.ui.choose;

import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Parcelable;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.basiclib.base.BaseActivity;
import com.android.basiclib.uitls.CommUtils;
import com.android.basiclib.uitls.Log.LogUtil;
import com.android.basiclib.uitls.NetWorkUtil;
import com.android.basiclib.uitls.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleIndicateCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleReadCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.smartpower.wattmeter.R;
import com.smartpower.wattmeter.utils.ByteUtil;
import com.smartpower.wattmeter.utils.CRC16Util;
import java.util.ArrayList;
import java.util.List;


/**
 * 选择了特征之后，进入操作页面
 */
public class CharacteOperationActivity extends BaseActivity {

    public static final int PROPERTY_READ = 1;
    public static final int PROPERTY_WRITE = 2;
    public static final int PROPERTY_WRITE_NO_RESPONSE = 3;
    public static final int PROPERTY_NOTIFY = 4;
    public static final int PROPERTY_INDICATE = 5;
    private static int charaProp = 0;
    private static BluetoothGattCharacteristic characteristic;

    private LinearLayout layout_container;
    private List<String> childList = new ArrayList<>();
    private BleDevice bleDevice;

    public static void startInstance(BleDevice bleDevice, BluetoothGattCharacteristic character, int type) {
        Context context = CommUtils.getContext();
        Intent intent = new Intent(context, CharacteOperationActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("bleDevice", bleDevice);
        charaProp = type;
        characteristic = character;
        context.startActivity(intent);
    }


    @Override
    protected void getDataFromIntent(Intent intent) {
        bleDevice = intent.getParcelableExtra("bleDevice");
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_operation;
    }

    @Override
    protected void init() {
        layout_container = findViewById(R.id.layout_container);
        View btn_wirte_zl = findViewById(R.id.btn_wirte_zl);
        btn_wirte_zl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                String jsonStr = "{\"hlz\": \"1x4\",\"byq\": \"7bd5351cb88a7073a6526b631e01527bd50cc82b29\",\"bdz\": \"0621426280\",\"yh\": \"1024839204\",\"xl\": \"0001222716\",\"wd\": \"30.870162644668973\",\"tq\": \"0001355947\",\"jd\": \"114.37234841525762\",\"zclx\": \"单体表箱\",\"zcbh\": \"1712020968\",\"sbmc\": \"计量箱\",\"sbcz\": \"热镀锌金属\"\n" +
//                        "}";
//                byte[] jsonStrByte = jsonStr.getBytes();
//                String hexJsonContentStr = ByteUtil.bytesToHex(jsonStrByte);
//                String hexLengthStr = Integer.toHexString(jsonStrByte.length);
//
//                //赋值长度
//                if (hexLengthStr.length() == 2) {
//                    hexLengthStr = hexLengthStr + "00";
//                } else if (hexLengthStr.length() == 3) {
//                    hexLengthStr = "0" + hexLengthStr;
//                    String substring1 = hexLengthStr.substring(0, 2);
//                    String substring2 = hexLengthStr.substring(2);
//                    hexLengthStr = substring2 + substring1;
//                } else if (hexLengthStr.length() == 4) {
//                    String substring1 = hexLengthStr.substring(0, 2);
//                    String substring2 = hexLengthStr.substring(2);
//                    hexLengthStr = substring2 + substring1;
//                }
//
//
//                String crc1 = CRC16Util.getCRC(ByteUtil.hexToBytes("A55A" + hexLengthStr + "03" + hexJsonContentStr));
//                String crc2 = CRC16Util.getCRC2(ByteUtil.hexToBytes("A55A" + hexLengthStr + "03" + hexJsonContentStr));
//                String crc3 = CRC16Util.getCRC3(ByteUtil.hexToBytes("A55A" + hexLengthStr + "03" + hexJsonContentStr));
//
//                String hexWriteStr = "A55A" + hexLengthStr + "03" + hexJsonContentStr + crc3 + "96";
//
//                LogUtil.w("hexLengthStr:" + hexLengthStr);
//                LogUtil.w("hexJsonContentStr:" + hexJsonContentStr);
//                LogUtil.w("crc1:" + crc1);
//                LogUtil.w("crc2:" + crc2);
//                LogUtil.w("crc3:" + crc3);
//                LogUtil.w("hexWriteStr:" + hexWriteStr);
//
//                BleManager.getInstance().write(
//                        bleDevice,
//                        characteristic.getService().getUuid().toString(),
//                        characteristic.getUuid().toString(),
//                        HexUtil.hexStringToBytes(hexWriteStr),   //写入数据为16进制
//                        new BleWriteCallback() {
//
//                            @Override
//                            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
//                                LogUtil.w("写入成功");
//                            }
//
//                            @Override
//                            public void onWriteFailure(final BleException exception) {
//                                LogUtil.w("写入数据命令失败:" + exception.getDescription());
//                            }
//                        });
            }
        });

        showData();
    }

    private void showData() {

        if (bleDevice != null && characteristic != null && charaProp != 0) {

            String child = characteristic.getUuid().toString() + String.valueOf(charaProp);

            for (int i = 0; i < layout_container.getChildCount(); i++) {
                layout_container.getChildAt(i).setVisibility(View.GONE);
            }
            if (childList.contains(child)) {
                layout_container.findViewWithTag(bleDevice.getKey() + characteristic.getUuid().toString() + charaProp).setVisibility(View.VISIBLE);
            } else {
                childList.add(child);

                View view = CommUtils.inflate(R.layout.layout_characteric_operation);
                view.setTag(bleDevice.getKey() + characteristic.getUuid().toString() + charaProp);
                LinearLayout layout_add = (LinearLayout) view.findViewById(R.id.layout_add);
                final TextView txt_title = (TextView) view.findViewById(R.id.txt_title);
                txt_title.setTextColor(Color.BLACK);
                txt_title.setText(String.valueOf(characteristic.getUuid().toString() + "的数据变化："));
                final TextView txt = (TextView) view.findViewById(R.id.txt);
                txt.setTextColor(Color.BLACK);
                txt.setMovementMethod(ScrollingMovementMethod.getInstance());

                switch (charaProp) {
                    case PROPERTY_READ: {
                        View view_add = CommUtils.inflate(R.layout.layout_characteric_operation_button);
                        Button btn = (Button) view_add.findViewById(R.id.btn);
                        btn.setText("读取");
                        btn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //读取
                                BleManager.getInstance().read(
                                        bleDevice,
                                        characteristic.getService().getUuid().toString(),
                                        characteristic.getUuid().toString(),
                                        new BleReadCallback() {

                                            @Override
                                            public void onReadSuccess(final byte[] data) {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        addText(txt, HexUtil.formatHexString(data, true));

                                                        handleNotifyData(data);
                                                    }
                                                });
                                            }

                                            @Override
                                            public void onReadFailure(final BleException exception) {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        addText(txt, exception.toString());
                                                    }
                                                });
                                            }
                                        });
                            }
                        });
                        layout_add.addView(view_add);
                    }
                    break;

                    case PROPERTY_WRITE: {
                        View view_add = CommUtils.inflate(R.layout.layout_characteric_operation_et);
                        final EditText et = (EditText) view_add.findViewById(R.id.et);
                        Button btn = (Button) view_add.findViewById(R.id.btn);
                        btn.setText("写入");
                        btn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //写入
                                String hex = et.getText().toString();
                                if (TextUtils.isEmpty(hex)) {
                                    return;
                                }
                                BleManager.getInstance().write(
                                        bleDevice,
                                        characteristic.getService().getUuid().toString(),
                                        characteristic.getUuid().toString(),
                                        HexUtil.hexStringToBytes(hex),   //写入数据为16进制
                                        new BleWriteCallback() {

                                            @Override
                                            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        addText(txt, "write success, current: " + current
                                                                + " total: " + total
                                                                + " justWrite: " + HexUtil.formatHexString(justWrite, true));
                                                    }
                                                });
                                            }

                                            @Override
                                            public void onWriteFailure(final BleException exception) {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        addText(txt, exception.toString());
                                                    }
                                                });
                                            }
                                        });
                            }
                        });
                        layout_add.addView(view_add);
                    }
                    break;

                    case PROPERTY_WRITE_NO_RESPONSE: {
                        View view_add = CommUtils.inflate(R.layout.layout_characteric_operation_et);
                        final EditText et = (EditText) view_add.findViewById(R.id.et);
                        Button btn = (Button) view_add.findViewById(R.id.btn);
                        btn.setText("写入无响应");
                        btn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                String hex = et.getText().toString();
                                if (TextUtils.isEmpty(hex)) {
                                    return;
                                }
                                BleManager.getInstance().write(
                                        bleDevice,
                                        characteristic.getService().getUuid().toString(),
                                        characteristic.getUuid().toString(),
                                        HexUtil.hexStringToBytes(hex),
                                        new BleWriteCallback() {

                                            @Override
                                            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        addText(txt, "write success, current: " + current
                                                                + " total: " + total
                                                                + " justWrite: " + HexUtil.formatHexString(justWrite, true));
                                                    }
                                                });
                                            }

                                            @Override
                                            public void onWriteFailure(final BleException exception) {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        addText(txt, exception.toString());
                                                    }
                                                });
                                            }
                                        });
                            }
                        });
                        layout_add.addView(view_add);
                    }
                    break;

                    case PROPERTY_NOTIFY: {
                        View view_add = CommUtils.inflate(R.layout.layout_characteric_operation_button);
                        final Button btn = (Button) view_add.findViewById(R.id.btn);
                        btn.setText("打开通知");
                        btn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (btn.getText().toString().equals("打开通知")) {
                                    btn.setText("关闭通知");
                                    //通知回调
                                    BleManager.getInstance().notify(
                                            bleDevice,
                                            characteristic.getService().getUuid().toString(),
                                            characteristic.getUuid().toString(),
                                            new BleNotifyCallback() {

                                                @Override
                                                public void onNotifySuccess() {

                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            addText(txt, "notify success");
                                                        }
                                                    });
                                                }

                                                @Override
                                                public void onNotifyFailure(final BleException exception) {

                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            addText(txt, exception.toString());
                                                        }
                                                    });
                                                }

                                                @Override
                                                public void onCharacteristicChanged(byte[] data) {

                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            String resultStr = HexUtil.formatHexString(characteristic.getValue(), true);
                                                            LogUtil.w("resultStr:" + resultStr);
                                                            addText(txt, resultStr);

                                                            handleNotifyData(data);
                                                        }
                                                    });
                                                }
                                            });
                                } else {
                                    //关闭通知
                                    btn.setText("打开通知");
                                    BleManager.getInstance().stopNotify(
                                            bleDevice,
                                            characteristic.getService().getUuid().toString(),
                                            characteristic.getUuid().toString());
                                }
                            }
                        });
                        layout_add.addView(view_add);
                    }
                    break;

                    case PROPERTY_INDICATE: {
                        View view_add = CommUtils.inflate(R.layout.layout_characteric_operation_button);
                        final Button btn = (Button) view_add.findViewById(R.id.btn);
                        btn.setText("打开通知");
                        btn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (btn.getText().toString().equals("打开通知")) {
                                    btn.setText("关闭通知");
                                    BleManager.getInstance().indicate(
                                            bleDevice,
                                            characteristic.getService().getUuid().toString(),
                                            characteristic.getUuid().toString(),
                                            new BleIndicateCallback() {

                                                @Override
                                                public void onIndicateSuccess() {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            addText(txt, "indicate success");
                                                        }
                                                    });
                                                }

                                                @Override
                                                public void onIndicateFailure(final BleException exception) {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            addText(txt, exception.toString());
                                                        }
                                                    });
                                                }

                                                @Override
                                                public void onCharacteristicChanged(byte[] data) {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            String resultStr = HexUtil.formatHexString(characteristic.getValue(), true);
                                                            LogUtil.w("resultStr:" + resultStr);
                                                            addText(txt, resultStr);

                                                            handleNotifyData(data);

                                                        }
                                                    });
                                                }
                                            });
                                } else {
                                    btn.setText("打开通知");
                                    BleManager.getInstance().stopIndicate(
                                            (BleDevice) bleDevice,
                                            characteristic.getService().getUuid().toString(),
                                            characteristic.getUuid().toString());
                                }
                            }
                        });
                        layout_add.addView(view_add);
                    }
                    break;
                }

                layout_container.addView(view);
            }
        }
    }


    StringBuilder allContent = new StringBuilder();
    int contentLenght = 1;

    //处理通知的接受数据
    private void handleNotifyData(byte[] data) {

        allContent.append(ByteUtil.bytesToHex(data));

//        buffer.writeBytes(data);

        if (data.length > 5 && ByteUtil.bytesToHex(ByteUtil.subBytes(data, 0, 2)).toUpperCase().equals("A55A")) {
            LogUtil.w("确定了帧头");
            //拿到长度信息
            String length1 = ByteUtil.bytesToHex(ByteUtil.subBytes(data, 2, 1));
            String length2 = ByteUtil.bytesToHex(ByteUtil.subBytes(data, 3, 1));
            //长度16进制转10进制
            contentLenght = Integer.parseInt(length2 + length1, 16);

            LogUtil.e("contentLenght:" + contentLenght);
        }

        if (ByteUtil.bytesToHex(ByteUtil.subBytes(data, data.length - 1, 1)).equals("96")) {
            LogUtil.w("确定了帧尾");

            //校验长度是否一致
            byte[] allBytes = ByteUtil.hexToBytes(allContent.toString());
            int allLength = allBytes.length;
            int subLength = allLength - 8;
            LogUtil.e("allLength:" + allLength);
            if (contentLenght == subLength) {
                //验证成功
                byte[] jsonBytes = ByteUtil.subBytes(allBytes, 5, subLength);
                String jsonStr = new String(jsonBytes);
                LogUtil.w("jsonStr:" + jsonStr);
            } else {
                //验证失败
                ToastUtils.makeText(mActivity, "长度验证失败");
            }
        }

    }

    private void addText(TextView textView, String content) {
        textView.append(content);
        textView.append("\n");
        int offset = textView.getLineCount() * textView.getLineHeight();
        if (offset > textView.getHeight()) {
            textView.scrollTo(0, offset - textView.getHeight());
        }
    }

    @Override
    public void onNetworkConnectionChanged(boolean isConnected, NetWorkUtil.NetworkType networkType) {
    }

    @Override
    protected void dataObserver() {
    }

}
